package mcia_gui;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import java.io.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Time;
import java.util.*;
import java.util.zip.*;
import javax.swing.UIManager;

/**
 * AdmAddFile.java - adding project zip file with definitions
 *
 * @author MCIA
 */
public class AdmAddFile extends javax.swing.JFrame {

    File file1G;
    File file2G;
    static final int BUFFER = 2048;                                             //file stream buffer size
    static final String strDirectory = "temp";                                  //directory with unziped files
    static File temp = new File(strDirectory);                                  //directory with unziped files
    private String dbName = "mcia";                                             //name of db we are connecting to
    private DatabaseEss db;                                                     //database definition
    private ArrayList<String> floorDescriptionsList = new ArrayList<String>();  //arraylist keeps srtings withe floor descriptions

    /** Creates new form Interface */
    public AdmAddFile() {
        initComponents();

        //emptying directory 'temp'
        if (emptyDirectory(temp)) {
            System.out.println("Temp empty.");
        } else {
            System.out.println("ERROR: temp not emptied.");
        }

        db = new DatabaseEss(dbName);                                           //declaring database

        //setting text in status label
        statusLabel.setText("User: " + LogOn.globalUsername);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        fileChooser2 = new javax.swing.JFileChooser();
        infoFrame = new javax.swing.JFrame();
        jPanel4 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        okButtonInfo = new javax.swing.JButton();
        errorInfoFrame = new javax.swing.JFrame();
        jPanel5 = new javax.swing.JPanel();
        jLabel10 = new javax.swing.JLabel();
        okButtonInfo1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        errorDescription = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        statusLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        Top = new javax.swing.JLabel();
        Back = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        AddProject = new javax.swing.JButton();
        fileNameTextField = new javax.swing.JLabel();
        loadButton = new javax.swing.JButton();

        fileChooser2.setAcceptAllFileFilterUsed(false);
        fileChooser2.setCurrentDirectory(new java.io.File("C:\\Users\\Jacek\\Downloads\\Projekt erazmusowy\\MCI\\Kamil_GUI\\test"));
        fileChooser2.setDialogTitle("Choose txt file");
        fileChooser2.setFileFilter(new MyCustomFilter2());

        infoFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        infoFrame.setTitle("Info");
        infoFrame.setLocationByPlatform(true);
        infoFrame.setMinimumSize(new java.awt.Dimension(354, 150));
        infoFrame.setName("MapView"); // NOI18N
        infoFrame.setResizable(false);

        jLabel9.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel9.setText("Settings Successfully Loaded!");

        okButtonInfo.setText("OK");
        okButtonInfo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonInfoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addGap(62, 62, 62)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(77, 77, 77)
                        .addComponent(okButtonInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(60, 60, 60))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(okButtonInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout infoFrameLayout = new javax.swing.GroupLayout(infoFrame.getContentPane());
        infoFrame.getContentPane().setLayout(infoFrameLayout);
        infoFrameLayout.setHorizontalGroup(
            infoFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        infoFrameLayout.setVerticalGroup(
            infoFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(infoFrameLayout.createSequentialGroup()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        errorInfoFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        errorInfoFrame.setTitle("Info");
        errorInfoFrame.setLocationByPlatform(true);
        errorInfoFrame.setMinimumSize(new java.awt.Dimension(390, 235));
        errorInfoFrame.setName("MapView"); // NOI18N
        errorInfoFrame.setResizable(false);

        jLabel10.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel10.setText("ERROR: Settings Not Loaded!");

        okButtonInfo1.setText("OK");
        okButtonInfo1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonInfo1ActionPerformed(evt);
            }
        });

        errorDescription.setBackground(new java.awt.Color(235, 233, 233));
        errorDescription.setColumns(20);
        errorDescription.setEditable(false);
        errorDescription.setFont(new java.awt.Font("Tahoma", 0, 12));
        errorDescription.setForeground(new java.awt.Color(51, 102, 255));
        errorDescription.setLineWrap(true);
        errorDescription.setRows(5);
        errorDescription.setText("Error Description");
        errorDescription.setWrapStyleWord(true);
        errorDescription.setBorder(null);
        jScrollPane1.setViewportView(errorDescription);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap(55, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(53, 53, 53))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap(165, Short.MAX_VALUE)
                .addComponent(okButtonInfo1, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(157, 157, 157))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(okButtonInfo1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout errorInfoFrameLayout = new javax.swing.GroupLayout(errorInfoFrame.getContentPane());
        errorInfoFrame.getContentPane().setLayout(errorInfoFrameLayout);
        errorInfoFrameLayout.setHorizontalGroup(
            errorInfoFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        errorInfoFrameLayout.setVerticalGroup(
            errorInfoFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(errorInfoFrameLayout.createSequentialGroup()
                .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MCIA LightControl");
        setBounds(new java.awt.Rectangle(200, 20, 800, 600));
        setMaximizedBounds(new java.awt.Rectangle(0, 0, 800, 600));
        setMinimumSize(new java.awt.Dimension(800, 600));
        setResizable(false);

        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        statusLabel.setText("User: Admin |  File upload");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
        );

        jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        Top.setFont(new java.awt.Font("Tahoma", 0, 18));
        Top.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        Top.setText("Import Project");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Top, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Top, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE)
                .addContainerGap())
        );

        Back.setText("Back");
        Back.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BackActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Choose project file to load", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        AddProject.setFont(new java.awt.Font("Tahoma", 0, 14));
        AddProject.setText("Add Project File");
        AddProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddProjectActionPerformed(evt);
            }
        });

        fileNameTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        fileNameTextField.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        fileNameTextField.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        fileNameTextField.setOpaque(true);

        loadButton.setFont(new java.awt.Font("Tahoma", 0, 14));
        loadButton.setText("Load");
        loadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(loadButton, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(AddProject, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(fileNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(AddProject, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(fileNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(loadButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(27, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(679, Short.MAX_VALUE)
                .addComponent(Back, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23))
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(90, 90, 90)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(98, Short.MAX_VALUE))
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(67, 67, 67)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(188, 188, 188)
                .addComponent(Back, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackActionPerformed
        AdmWelcome aafilescreen = new AdmWelcome();
        Main.changeFrame(aafilescreen);
    }//GEN-LAST:event_BackActionPerformed

    private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed
        //getting screen resolution
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension scrnsize = toolkit.getScreenSize();
        errorInfoFrame.setLocation(scrnsize.width / 2 - (errorInfoFrame.getWidth() / 2), scrnsize.height / 2 - (errorInfoFrame.getHeight() / 2));

        if (fileNameTextField.getText().isEmpty()) {
            errorInfoFrame.setVisible(true);
            errorDescription.setText("No file choosen!");
            return;
        }

        loadButton.setEnabled(false);

        //creating directory for storing files
        try {
            boolean success = (temp).mkdir();
            if (success) {
                System.out.println("Directory " + strDirectory + " created:" + temp.getAbsolutePath());
            } else {
                System.out.println("Directory: " + strDirectory + " not created, probably it exists.");
            }
        } catch (Exception e) {       //Catch exception if any
            errorInfoFrame.setVisible(true);
            errorDescription.setText(e.toString());
            System.err.println("Error: " + e.getMessage());
            return;
        }
        //---------------------unzip----------------------------
        try {
            BufferedOutputStream dest = null;
            BufferedInputStream is = null;
            ZipEntry entry;
            ZipFile zipfile = new ZipFile(file2G);
            Enumeration e = zipfile.entries();
            while (e.hasMoreElements()) {
                entry = (ZipEntry) e.nextElement();
                is = new BufferedInputStream(zipfile.getInputStream(entry));
                int count;
                byte data[] = new byte[BUFFER];
                File temporary = new File("temp", entry.getName());
                FileOutputStream fos = new FileOutputStream(temporary);
                dest = new BufferedOutputStream(fos, BUFFER);
                while ((count = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
                is.close();
            }
        } catch (Exception e) {
            errorInfoFrame.setVisible(true);
            errorDescription.setText(e.toString());
            System.out.println("Error: " + e);
            return;
        }
        //-----------------------end of unzipping--------------------

        //emptying database tables

        //DELETE FROM units
        try {
            db.stmt = db.conn.createStatement();
            String truncate_query = "DELETE FROM units";
            int results0 = db.stmt.executeUpdate(truncate_query);
            if (results0 == 0) {
                System.out.println("Records from 'units' not deleted!");
            } else {
                System.out.println("Table 'units' empty.");
            }
            db.stmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(AdmAddFile.class.getName()).log(Level.SEVERE, null, ex);
        }
        //DELETE FROM local_scenes
        try {
            db.stmt = db.conn.createStatement();
            String truncate_query = "DELETE FROM local_scenes";
            int results1 = db.stmt.executeUpdate(truncate_query);
            if (results1 == 0) {
                System.out.println("Records from 'local_scenes' not deleted!");
            } else {
                System.out.println("Table 'local_scenes' empty.");
            }
            db.stmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(AdmAddFile.class.getName()).log(Level.SEVERE, null, ex);
        }
        //DELETE FROM local_memberships
        try {
            db.stmt = db.conn.createStatement();
            String truncate_query = "DELETE FROM local_memberships";
            int results2 = db.stmt.executeUpdate(truncate_query);
            if (results2 == 0) {
                System.out.println("Records from 'local_memberships' not deleted!");
            } else {
                System.out.println("Table 'local_memberships' empty.");
            }
            db.stmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(AdmAddFile.class.getName()).log(Level.SEVERE, null, ex);
        }
        //DELETE FROM global_scenes
        try {
            db.stmt = db.conn.createStatement();
            String truncate_query = "DELETE FROM global_scenes";
            int results1 = db.stmt.executeUpdate(truncate_query);
            if (results1 == 0) {
                System.out.println("Records from 'global_scenes' not deleted!");
            } else {
                System.out.println("Table 'global_scenes' empty.");
            }
            db.stmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(AdmAddFile.class.getName()).log(Level.SEVERE, null, ex);
        }
        //DELETE FROM global_memberships
        try {
            db.stmt = db.conn.createStatement();
            String truncate_query = "DELETE FROM global_memberships";
            int results2 = db.stmt.executeUpdate(truncate_query);
            if (results2 == 0) {
                System.out.println("Records from 'global_memberships' not deleted!");
            } else {
                System.out.println("Table 'global_memberships' empty.");
            }
            db.stmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(AdmAddFile.class.getName()).log(Level.SEVERE, null, ex);
        }


        //getting floor descriptions into variable
        File descFile = new File("temp", "floorDesc.txt");
        if (descFile.exists()) {
            try {
                System.out.println("Sucessfully accessed txt file: " + descFile);
                FileReader fr = new FileReader(descFile);
                BufferedReader br = new BufferedReader(fr);
                String dbRecord;
                int lineCount = 0;

                while ((dbRecord = br.readLine()) != null) {
                    //accessing file with floor descriptions
                    StringTokenizer st = new StringTokenizer(dbRecord, ";");

                    while (st.hasMoreTokens()) {
                        lineCount++;
                        String token = st.nextToken();
                        if (st.hasMoreTokens()) {
                            String token2 = st.nextToken();
                            floorDescriptionsList.add(token + ". " + token2);
                        } else {
                            floorDescriptionsList.add("");
                        }
                    }
                }
            } catch (Exception ex) {
                errorInfoFrame.setVisible(true);
                errorDescription.setText("Error with file: " + ex + " Filename: floorDesc.txt");
                System.out.println("Error with file: " + ex + " Filename: floorDesc.txt");
                return;
            }
        } else {
            //file doesn't exits
            System.out.println("WARNING: File with floor descriptions not found.");
        }

        //what we do with unzipped files
        String files[] = temp.list();
        for (int i = 0; i < files.length; i++) {

            int firstLine = 1;
            int gsFirstLine = 0;
            File sourcefile = new File("temp", files[i]);
            if (sourcefile.getName().endsWith(".txt")) {
                //what to do with txt file
                try {
                    System.out.println("Sucessfully accessed txt file: " + sourcefile);
                    FileReader fr = new FileReader(sourcefile);
                    BufferedReader br = new BufferedReader(fr);

                    int floorNo, clNo, lightNo, xCoord, yCoord;
                    String dbRecord;
                    int insertedGSceneID = -1;
                    //if we have empty floor
                    if (sourcefile.length() == 0 && files[i].endsWith(".txt") && !files[i].startsWith("LS") && !files[i].startsWith("GS") && !files[i].startsWith("CL") && !files[i].startsWith("floorDesc")) {
                        String desc;
                        int floorNumber = Integer.parseInt(files[i].substring(0, files[i].length() - 4));
                        String img = files[i].substring(0, files[i].length() - 3);
                        img = img + "jpg";

                        //putting data into database without image
                        if (floorDescriptionsList.size() > 0 && !floorDescriptionsList.get(floorNumber).isEmpty()) {
                            desc = floorDescriptionsList.get(floorNumber);
                        } else {
                            desc = floorNumber + ".";
                        }
                        insertIntoDb(floorNumber, 0, 0, img, 0, 0, desc);
                    }
                    //reading txt config file
                    while ((dbRecord = br.readLine()) != null) {
                        if (files[i].length() > 2 && files[i].substring(0, 2).equals("LS")) {
                            //accessing LSx.x.txt file (with local scenes)------------------------------------------------------
                            StringTokenizer st = new StringTokenizer(dbRecord, ";");

                            int tokenCount = 0;
                            int insertedSceneID = -1;
                            while (st.hasMoreTokens()) {
                                tokenCount++;
                                try {
                                    if (tokenCount == 1) {
                                        String token = st.nextToken();
                                        //getting floor and cl number
                                        int dot = files[i].indexOf(".");
                                        int floor = Integer.parseInt(files[i].substring(2, dot));
                                        int dot2 = files[i].lastIndexOf(".");
                                        int cl = Integer.parseInt(files[i].substring(dot + 1, dot2));
                                        //inserting sceneName into db
                                        insertedSceneID = insertLocalSceneName("CL " + floor + "." + cl + ": " + token);
                                    } else {
                                        int lightNumber = Integer.parseInt(st.nextToken());
                                        int lightBright = Integer.parseInt(st.nextToken());
                                        int lightTimm = Integer.parseInt(st.nextToken());
                                        //getting floor and cl number
                                        int dot = files[i].indexOf(".");
                                        int floor = Integer.parseInt(files[i].substring(2, dot));
                                        int dot2 = files[i].lastIndexOf(".");
                                        int cl = Integer.parseInt(files[i].substring(dot + 1, dot2));
                                        //inserting into db
                                        insertLocalScene(insertedSceneID, lightNumber, lightBright, lightTimm, floor, cl);
                                    }
                                } catch (Exception ex) {
                                    System.out.println("Error with parsing scene file: " + files[i] + " Message: " + ex);
                                }
                            }
                        } else if (files[i].length() > 2 && files[i].substring(0, 2).equals("GS")) {
                            //for Global Scene files----------------------------------------------------------------------------
                            StringTokenizer st = new StringTokenizer(dbRecord, ";");

                            while (st.hasMoreTokens()) {
                                try {
                                    if (gsFirstLine == 0) {
                                        String token0 = st.nextToken(); //globals scene name
                                        //inserting sceneName into db
                                        insertedGSceneID = insertGlobalSceneName(token0);
                                        gsFirstLine = 1;
                                    } else {
                                        int floorNumber = Integer.parseInt(st.nextToken());
                                        int clNumber = Integer.parseInt(st.nextToken());
                                        String lsName = st.nextToken(); //local scene name
                                        lsName = "CL " + floorNumber + "." + clNumber + ": " + lsName;
                                        String timeSch = st.nextToken();
                                        //inserting into db
                                        insertGlobalScene(insertedGSceneID, lsName, floorNumber, clNumber, timeSch);
                                    }
                                } catch (Exception ex) {
                                    System.out.println("Error with parsing global scene file: " + files[i] + " Message: " + ex);
                                }
                            }
                        } else if (files[i].length() > 2 && !files[i].equals("floorDesc.txt")) {
                            //accessing other txt file (with Floor or CL)-------------------------------------------------------
                            StringTokenizer st = new StringTokenizer(dbRecord, ";");

                            String floor = st.nextToken();
                            String clName = st.nextToken();
                            String Light = st.nextToken();
                            String X = st.nextToken();
                            String Y = st.nextToken();

                            floorNo = Integer.parseInt(floor);
                            clNo = Integer.parseInt(clName);
                            lightNo = Integer.parseInt(Light);
                            xCoord = Integer.parseInt(X);
                            yCoord = Integer.parseInt(Y);

                            int countDots = files[i].indexOf(".");
                            int countDots2 = files[i].substring(Math.abs(countDots) + 1).indexOf(".");

                            String desc;

                            if (countDots2 > 0) { //CL file
                                //putting data into database
                                desc = "Light " + lightNo;
                                insertIntoDb(floorNo, clNo, lightNo, null, xCoord, yCoord, desc);
                            } else { //floor file (with possible CLs)
                                //only once adding floor
                                if (firstLine == 1) {
                                    String img = files[i].substring(0, files[i].length() - 3);
                                    img = img + "jpg";

                                    //putting data into database without image
                                    if (floorDescriptionsList.size() > 0 && !floorDescriptionsList.get(floorNo).isEmpty()) {
                                        desc = floorDescriptionsList.get(floorNo);
                                    } else {
                                        desc = floorNo + ".";
                                    }
                                    insertIntoDb(floorNo, 0, 0, img, 0, 0, desc);
                                }
                                //if CL adding CL with image
                                if (lightNo == 0) {
                                    String img = "CL " + floorNo + "." + clNo + ".jpg";
                                    //putting data into database with image
                                    desc = "CL " + clNo;
                                    insertIntoDb(floorNo, clNo, lightNo, img, xCoord, yCoord, desc);
                                } else {
                                    //putting data into database without image
                                    desc = "Light " + lightNo;
                                    insertIntoDb(floorNo, clNo, lightNo, null, xCoord, yCoord, desc);
                                }
                            }

                            firstLine = 0;
                        } else {
                            //for other files - ignore--------------------------------------------------------------------------
                        }
                    }
                } catch (Exception ex) {
                    errorInfoFrame.setVisible(true);
                    errorDescription.setText("Error with file: " + ex + " Filename: " + files[i]);
                    System.out.println("Error with file: " + ex + " Filename: " + files[i]);
                    return;
                }
            } else if (sourcefile.getName().endsWith(".jpg")) {
                //we do nothing with jpg file
            } else {
                //other extension than .txt and than .jpg
                System.out.println("Other file extension: " + sourcefile);
            }

            //showing and positioning info frame
            infoFrame.setVisible(true);
            infoFrame.setLocation(scrnsize.width / 2 - (infoFrame.getWidth() / 2), scrnsize.height / 2 - (infoFrame.getHeight() / 2));


        }

    }//GEN-LAST:event_loadButtonActionPerformed

    private void AddProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddProjectActionPerformed
        int returnVal = fileChooser2.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file2 = fileChooser2.getSelectedFile();
            file2G = file2;

            fileNameTextField.setText(file2.getName());
            System.out.println("File accessed: " + file2.getAbsolutePath());

        } else {
            System.out.println("File access cancelled by user.");
        }
}//GEN-LAST:event_AddProjectActionPerformed

    private void okButtonInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonInfoActionPerformed
        //closing info
        infoFrame.dispose();
    }//GEN-LAST:event_okButtonInfoActionPerformed

    private void okButtonInfo1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonInfo1ActionPerformed
        //hiding
        errorInfoFrame.dispose();
    }//GEN-LAST:event_okButtonInfo1ActionPerformed

    public int insertGlobalSceneName(String sceneName) {
        int recordID = -1;
        try {
            //inserting record
            String query = "INSERT INTO global_scenes (NAME) VALUES ('" + sceneName + "')";
            System.out.println(query);

            PreparedStatement ps = db.conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
            ps.executeUpdate();

            ResultSet rs = ps.getGeneratedKeys();
            if (rs.next()) {
                recordID = rs.getInt(1);
            }
            rs.close();
            ps.close();
        } catch (SQLException ex) {
            System.out.println("Error inseting: " + ex + " Code: " + ex.getMessage());
            return -1;
        }
        return recordID;
    }

    public int insertLocalSceneName(String sceneName) {
        int recordID = -1;
        try {
            //inserting record
            String query = "INSERT INTO local_scenes (NAME) VALUES ('" + sceneName + "')";

            PreparedStatement ps = db.conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
            ps.executeUpdate();

            ResultSet rs = ps.getGeneratedKeys();
            if (rs.next()) {
                recordID = rs.getInt(1);
            }
            rs.close();
            ps.close();
        } catch (SQLException ex) {
            System.out.println("Error inseting: " + ex + " Code: " + ex.getMessage());
            return -1;
        }
        return recordID;
    }

    public int insertGlobalScene(int gsID, String lsName, int lsFloor, int lsCL, String timer) {
        int recordID = -1;
        try {
            //inserting record
            String query = "INSERT INTO global_memberships (GS_ID, LS_NAME, LS_FLOOR, LS_CL, TIME) VALUES (" + gsID + ",'" + lsName + "'," + lsFloor + "," + lsCL + ",?)";

            PreparedStatement ps = db.conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
            Time scheduledTime = Time.valueOf(timer);
            ps.setTime(1, scheduledTime);
            ps.executeUpdate();

            ResultSet rs = ps.getGeneratedKeys();
            if (rs.next()) {
                recordID = rs.getInt(1);
            }
            rs.close();
            ps.close();
        } catch (SQLException ex) {
            System.out.println("Error inseting: " + ex + " Code: " + ex.getMessage());
            return -1;
        }
        return recordID;
    }

    public int insertLocalScene(int lsID, int lightNo, int lightBrightness, int lightTimer, int floor, int cl) {
        int recordID = -1;
        try {
            //inserting record
            String query = "INSERT INTO local_memberships (LS_ID, BRIGHTNESS, UNIT_FLOOR, UNIT_CL, UNIT_LIGHT) VALUES (" + lsID + "," + lightBrightness + "," + floor + "," + cl + "," + lightNo + ")";

            PreparedStatement ps = db.conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
            ps.executeUpdate();

            ResultSet rs = ps.getGeneratedKeys();
            if (rs.next()) {
                recordID = rs.getInt(1);
            }
            rs.close();
            ps.close();
        } catch (SQLException ex) {
            System.out.println("Error inseting: " + ex + " Code: " + ex.getMessage());
            return -1;
        }
        return recordID;
    }

    public int insertIntoDb(int floorNo, int clNo, int light, String img, int px, int py, String desc) {

        try {
            //inserting record
            db.stmt = db.conn.createStatement();

            if (desc == null) {
                desc = "";
            }

            String query = "INSERT INTO units (FLOOR, CL, LIGHT, DESCRIPTION, PX, PY) VALUES (" + floorNo + ", " + clNo + ", " + light + ", '" + desc + "', " + px + ", " + py + ")";
            int results = db.stmt.executeUpdate(query);

            if (results == 0) {
                System.out.println("Record not inserted!");
                return -1;
            } else {
                System.out.println("Unit inserted into db: " + floorNo + " " + clNo + " " + light);
            }

            db.stmt.close();
        } catch (SQLException ex) {
            System.out.println("Error inseting: " + ex + " Code: " + ex.getMessage());
        }

        boolean exists;
        if (img != null) {
            exists = (new File("temp", img)).exists();
        } else {
            exists = false;
        }

        if (exists == false) {
            System.out.println("No image file - no inserted: " + img);
        }
        if (img != null && exists) {
            //inserting image
            File file = new File("temp", img);

            int fileLength = (int) file.length();
            try {
                InputStream fin = new FileInputStream(file);

                db = new DatabaseEss(dbName);
                PreparedStatement ps;
                try {
                    ps = db.conn.prepareStatement("UPDATE units SET image = ? WHERE floor = " + floorNo + " AND cl = " + clNo + " AND light = " + light + "");
                    ps.setBinaryStream(1, fin, fileLength);
                    ps.execute();
                } catch (SQLException ex) {
                    Logger.getLogger(ManagerLSView.class.getName()).log(Level.SEVERE, null, ex);
                }


            } catch (FileNotFoundException ex) {
                Logger.getLogger(ManagerLSView.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        //if everything is OK
        return 0;
    }

    static public boolean emptyDirectory(File path) {
        if (path.exists()) {
            File[] files = path.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    emptyDirectory(files[i]);
                } else {
                    try {
                        if (files[i].delete()) {
                            System.out.println("File " + files[i].getAbsolutePath() + " was deleted.");
                        } else {
                            System.out.println("File " + files[i].getAbsolutePath() + " wasn't deleted. Problem occured.");
                        }
                    } catch (Exception ex) {
                        System.err.println("Unable to delete " + files[i] + "(" + ex.getMessage() + ")");
                    }
                }
            }
        }
        return (true);
    }

    public static void main(String args[]) {
        //setting Windows Look and Feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println("Error setting native LAF: " + ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    //new AdmWelcome().setVisible(true);
                    LogOn thisFrame = new LogOn();
                    String[] vars = null;
                    Main.main(vars);
                    Main.changeFrame(thisFrame);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(AdmWelcome.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(AdmWelcome.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddProject;
    private javax.swing.JButton Back;
    private javax.swing.JLabel Top;
    private javax.swing.JTextArea errorDescription;
    private javax.swing.JFrame errorInfoFrame;
    private javax.swing.JFileChooser fileChooser2;
    private javax.swing.JLabel fileNameTextField;
    private javax.swing.JFrame infoFrame;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton loadButton;
    private javax.swing.JButton okButtonInfo;
    private javax.swing.JButton okButtonInfo1;
    private javax.swing.JLabel statusLabel;
    // End of variables declaration//GEN-END:variables
}
